<template>
    <div>
        <van-search placeholder="请输入搜索关键词" v-model="key" show-action @search="onSearch" @cancel="onClear" @clear="onClear"/>

        <van-list finished-text="没有更多了">
            <van-swipe-cell v-for="item in searchList" :key="item.id" >
                <van-cell :title="item.name" :value="'商品上架时间：' + item.ctime.substr(0, 10)" />
                <template slot="right">
                    <van-button square type="danger" text="删除" @click="delproduct(item.id)" />
                </template>
            </van-swipe-cell>
        </van-list>

        <div class="searchHistory" v-show="isShowBar">
            <div class="top">
                <p>搜索历史</p>
                <van-icon name="delete" @click="clearHistory"/>
            </div>
            <div class="tagList">
                <van-tag plain type="primary" v-for="(item, index) in searchHistory" :key="index">{{item}}</van-tag>
                <van-divider v-show="isShowHistory">暂未搜索历史</van-divider>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            key: '',
            searchList: [],
            searchHistory: [],
        }
    },
    computed: {
        isShowBar() {
            return this.searchList.length === 0 ? true : false; 
        },
        isShowHistory() {
            return this.searchHistory.length === 0 ? true : false; 
        },
    },
    methods: {
        async onSearch() {
            if (this.key.trim() === "") {
                this.searchList = [];
                this.$toast('搜索内容不能为空');
                return;
            }
            const {data: res} = await this.$http.get('/api/getprodlist');
            this.searchList = res.message;
            if (!this.searchHistory.includes(this.key)) {
                this.searchHistory.push(this.key);
            }
        },
        onClear() {
            this.searchList = [];
        },
        delproduct(id) {
            this.$dialog.confirm({
                title: '警告',
                message: '是否删除该商品',
            }).then(async () => {
                const {data: res} = await this.$http.get('/api/delproduct/' + id);
                const index = this.searchList.findIndex(item => item.id === id);
                this.searchList.splice(index, 1);
                this.$notify({ type: 'success', message: '删除成功' });
            }).catch(() => {
                this.$notify({ type: 'danger', message: '取消删除' });
            });
        },
        clearHistory() {
            this.searchHistory = [];
        }
    }
}
</script>

<style lang="less" scoped>
.searchHistory {
    .top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10px;
    }
    .tagList {
        margin: 5px 10px;

        .van-tag {
            margin: 0 5px;
        }
    }
    
}
</style>